import logging

import cherrypy

import turbogears
from turbogears import controllers, expose, validate, redirect
from turbogears import identity

from actionflow import json, taskwidgets
from actionflow.model import *

log = logging.getLogger("actionflow.controllers")

class Root(controllers.RootController):
    @expose("actionflow.templates.index")
    def index(self):
        return dict()
    
    @expose("actionflow.templates.list_by_project")
    def project(self):
        return dict(projects=Project.select(Project.q.completed == False))
    
    @expose()
    def task(self):
        return dict(tasks=Task.select(Task.q.completed == False))
    
    @expose(template="actionflow.templates.form")
    def task_form(self, ID):
        submit_action = "/save_task"
        if ID == "new":
            values =""
            return dict(form=taskwidgets.task_form, values=values, action=submit_action)
        else:
          values = Task.get(int(ID))
          return dict(form=taskwidgets.task_form, values=values, action=submit_action)
      
    @expose()
    def save_task(self, **kwargs):
        Task(**kwargs)

    @expose()
    def project_form(self, ID):
        if ID == "new":
            return "Form for adding new task"
        else:
          Project.get(int(ID))
          return "form for editing an existing task"

    @expose(allow_json=True)
    def search_project(self, search):
        matching_projects = Project.select(Project.q.name.startswith(search))
        project_names = [project.name for project in matching_projects]
        return dict(projects=project_names)

    @expose(allow_json=True)
    def search_context(self, search):
        matching_contexts = Context.select(Context.q.name.startswith(search))
        Context_names = [context.name for context in matching_contexts]
        return dict(projects=project_names)


    @expose()
    def save_project(self):
        turbogears.flash("Project added")
        redirect("/tasks")
    
    @expose()
    def context(self):
        return "context page goes here"
    
    @expose()
    def projects_without_tasks(self):
        return dict(contexts=Context.select())
    
    @expose(template="actionflow.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url=None
        previous_url= cherrypy.request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= cherrypy.request.headers.get("Referer", "/")
        cherrypy.response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=cherrypy.request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect("/")
